const {exec, escape} = require("../db/mysql")

// 账户登录
const login = async ({username, password}) => {
    // security: sql注入
    username = escape(username)
    password = escape(password)
    const sql = `
        select username, rolename
        from user
        where username = ${username}
          and password = ${password}
          and isdel = 0;`
    return await exec(sql).then(rows => {
        return rows[0] || {}
    })
}
// 获取所有账户信息
const getAccountList = async () => {
    const sql = `select *
                 from user;`
    return await exec(sql)
}
// 修改账户密码
const updateAccountPassword = async ({username, password}) => {
    // sql注入安全问题，不考虑加密
    username = escape(username)
    password = escape(password)
    const sql = `update user
                 set password = ${password}
                 where username = ${username}`
    return await exec(sql).then(rows => {
        if (rows.affectedRows > 0) {
            return true
        } else {
            return false
        }
    })
}
// 删除账户
const deleteAccount = async (id) => {
    const sql = `update user
                 set isdel = 1
                 where id = ${id}`
    return await exec(sql).then(rows => {
        if (rows.affectedRows > 0) {
            return true
        } else {
            return false
        }
    })
}

// 添加账户
const newAccount = async ({username, password, rolename}) => {
    // sql注入安全问题，不考虑加密
    username = escape(username)
    password = escape(password)
    rolename = escape(rolename)
    const create_time = new Date().toISOString().slice(0, 10)
    const sql = `insert into user(username, password, rolename, create_time, isdel)
                 values (${username}, ${password}, ${rolename}, '${create_time}', 0);`
    return await exec(sql).then(rows => {
        return {id: rows.insertId}
    })
}
const getAccountDetail = async (username) => {
    username = escape(username)
    const sql = `select * from user where username = ${username}`
    return await exec(sql).then(rows => {
        return rows[0] || {}
    })
}

// 根据身份证号删除账户（学员或教练）
const deleteAccountByUsername = async (username) => {
    username = escape(username)
    const sql = `update user
                 set isdel = 1
                 where username = ${username}`
    return await exec(sql).then(rows => {
        if (rows.affectedRows > 0) {
            return true
        } else {
            return false
        }
    })
}

module.exports = {
    getAccountList,
    getAccountDetail,
    login,
    newAccount,
    updateAccountPassword,
    deleteAccount,
    deleteAccountByUsername
}
